const { Sequelize } = require('sequelize')
const config = require('./index')
const logger = require('../utils/logger')

// MySQL数据库配置
const dbConfig = {
  host: process.env.DB_HOST || 'localhost',
  port: parseInt(process.env.DB_PORT) || 3306,
  database: process.env.DB_NAME || 'course_lectures',
  username: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || '',
  dialect: 'mysql',
  logging: (msg) => logger.info(msg),
  pool: {
    max: 10,
    min: 0,
    acquire: 30000,
    idle: 10000
  },
  timezone: '+08:00',
  define: {
    timestamps: true,
    underscored: false,
    freezeTableName: true,
    charset: 'utf8mb4',
    collate: 'utf8mb4_unicode_ci'
  }
}

// 创建Sequelize实例
const sequelize = new Sequelize(
  dbConfig.database,
  dbConfig.username,
  dbConfig.password,
  {
    host: dbConfig.host,
    port: dbConfig.port,
    dialect: dbConfig.dialect,
    logging: dbConfig.logging,
    pool: dbConfig.pool,
    timezone: dbConfig.timezone,
    define: dbConfig.define
  }
)

// 测试数据库连接
async function testConnection() {
  try {
    await sequelize.authenticate()
    logger.info('MySQL数据库连接成功')
    return true
  } catch (error) {
    logger.error('MySQL数据库连接失败:', error)
    return false
  }
}

// 同步数据库模型
async function syncDatabase(force = false) {
  try {
    await sequelize.sync({ force })
    logger.info('数据库模型同步成功')
    return true
  } catch (error) {
    logger.error('数据库模型同步失败:', error)
    return false
  }
}

// 关闭数据库连接
async function closeConnection() {
  try {
    await sequelize.close()
    logger.info('数据库连接已关闭')
  } catch (error) {
    logger.error('关闭数据库连接失败:', error)
  }
}

module.exports = {
  sequelize,
  testConnection,
  syncDatabase,
  closeConnection
}